/*
	Copyright 2010 by Robin W. Spencer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You can find a copy of the GNU General Public License
    at http://www.gnu.org/licenses/.

*/
  
//parameters  
  var canvas = document.getElementById('scheduleCanvas');
  var coordinates = new Array();
  var dayWidth = 144;    
  var hourWidth = dayWidth/24;
  var startPosX = 30;
  var startPosY = 240;
  var weekDayPos = startPosX + (dayWidth/2) - 10;
  var numberOfDays = 7;
  var halfHeight = 100;
  var tenPercHeight = halfHeight/5;
  var drawingLimitX = startPosX + numberOfDays * dayWidth;
  var drawingLimitY = startPosY - 2 * halfHeight;  
  canvas.width = drawingLimitX + 30;
  canvas.height = 270;
  var originalCanvasHeight = 270;
  var t=0.3;
  canvas.parentNode.style.width=canvas.width+"px";  //  The div around the canvas element should fit snugly.
  var ctx = canvas.getContext('2d');
  var results;
  var result = new Array();
  var presentedResults=false;
  var surveyInfo;
  var colors = ["#ffb0a1", "#5c2c00", " #a6ffbf", "#7a5e85",
                "#cf36ff", "#329932", "#5a9e68", "#005710"];
  getSurveyInfo();
  drawChart(ctx);

function deleteButtonIfClosed() {
	if (surveyInfo['status'] == 'Closed') {
		var element = document.getElementById('closeButton');
		element.parentNode.removeChild(element);
	}
}  
  
function drawChart(ctx) {
	ctx.lineWidth=2;
    ctx.font = '10pt Calibri';

    ctx.fillStyle = '#EEEEEE';
    ctx.rect(startPosX, startPosY - 2 * halfHeight, (numberOfDays * dayWidth), 2 * halfHeight);
    ctx.fill();
    //ctx.stroke();
    ctx.fillStyle = 'black';    
    ctx.fillText("Mon", weekDayPos, startPosY+30);
    ctx.fillText("Tue", weekDayPos + dayWidth, startPosY+30);
    ctx.fillText("Wed", weekDayPos + (2 * dayWidth), startPosY+30);
    ctx.fillText("Thu", weekDayPos + (3 * dayWidth), startPosY+30);
    ctx.fillText("Fri", weekDayPos + (4 * dayWidth), startPosY+30);
    ctx.fillText("Sat", weekDayPos + (5 * dayWidth), startPosY+30);
    ctx.fillText("Sun", weekDayPos + (6 * dayWidth), startPosY+30);
    ctx.beginPath();
    ctx.moveTo(startPosX, 0);
    ctx.lineTo(startPosX, startPosY);
    ctx.lineTo(startPosX + (numberOfDays * dayWidth) + 20, startPosY);
    ctx.stroke();
    ctx.closePath();    
//strza�ka na osi poziomej
    ctx.beginPath();
    ctx.moveTo(startPosX + (numberOfDays * dayWidth) + 20, startPosY);
    ctx.lineTo(startPosX + (numberOfDays * dayWidth) +10, startPosY -5);
    ctx.stroke();
    ctx.closePath();      

    ctx.beginPath();
    ctx.moveTo(startPosX + (numberOfDays * dayWidth) + 20, startPosY);
    ctx.lineTo(startPosX + (numberOfDays * dayWidth) +10, startPosY +5);
    ctx.stroke();
    ctx.closePath();      
//srza�ka na osi pionowej
    ctx.beginPath();
    ctx.moveTo(startPosX, 0);
    ctx.lineTo(startPosX + 5, 10);
    ctx.stroke();
    ctx.closePath();      

    ctx.beginPath();
    ctx.moveTo(startPosX, 0);
    ctx.lineTo(startPosX - 5, 10);    ctx.stroke();
    ctx.closePath();    
    
    
    ctx.beginPath();
    ctx.moveTo(startPosX, startPosY);
    ctx.lineTo(startPosX, startPosY+15);
    ctx.stroke();
    ctx.closePath();    
    
    // pozioma skala
    for(var i=1;i<=7;++i){
        ctx.beginPath();
        var position = i * dayWidth;
        ctx.moveTo(startPosX + position, startPosY);
        ctx.lineTo(startPosX + position, startPosY+15);
        ctx.stroke();
        ctx.closePath();

        for(var j=0;j<24;++j){
            position = (i-1) * dayWidth + j * hourWidth;
        	if (j==3) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("3", startPosX + position - 3, startPosY+15);
            }        	
            if (j==6) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("6", startPosX + position - 3, startPosY+15);
            }
            if (j==9) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("9", startPosX + position - 3, startPosY+15);
            }            
            if (j==12) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("12", startPosX + position - 6, startPosY+15);
            }
            if (j==15) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("15", startPosX + position - 6, startPosY+15);
            }            
            if (j==18) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';            	
            	ctx.fillText("18", startPosX + position - 6, startPosY+15);
            }
            if (j==21) {
                ctx.font = '8pt Calibri';
                ctx.fillStyle = 'black';
            	ctx.fillText("21", startPosX + position - 6, startPosY+15);
            }            
        	ctx.beginPath();
            ctx.moveTo(startPosX + position, startPosY);
            ctx.lineTo(startPosX + position, startPosY+5);
            ctx.stroke();
            ctx.closePath();
        }
    }
    
    //pionowa skala
    for(var i=0;i<=2;++i){
        ctx.beginPath();
        var position = i * halfHeight;
        ctx.moveTo(startPosX, startPosY - position);
        ctx.lineTo(startPosX - 10, startPosY - position);
        ctx.stroke();
        ctx.closePath();
        
        if (i==0) {
            ctx.font = '10pt Calibri';
            ctx.fillStyle = 'black';
        	ctx.fillText("0", startPosX - 30, startPosY - position+5);
        }
        if (i==1) {
            ctx.font = '10pt Calibri';
            ctx.fillStyle = 'black';
        	ctx.fillText("0.5", startPosX - 30, startPosY - position+5);
        }
        if (i==2) {
            ctx.font = '10pt Calibri';
            ctx.fillStyle = 'black';
        	ctx.fillText("1", startPosX - 30, startPosY - position+5);
        }        
        


        for(var j=0;j<5 && i<2;++j){           
        	ctx.beginPath();
            var position = i * halfHeight + j * tenPercHeight;
            ctx.moveTo(startPosX, startPosY - position);
            ctx.lineTo(startPosX - 5, startPosY - position);
            ctx.stroke();
            ctx.closePath();
        }
    }
}

    function hexToCanvasColor(hexColor,opacity){
        // Convert #AA77CC to rbga() format for Firefox
        opacity=opacity || "1.0";
        hexColor=hexColor.replace("#","");
        var r=parseInt(hexColor.substring(0,2),16);
        var g=parseInt(hexColor.substring(2,4),16);
        var b=parseInt(hexColor.substring(4,6),16);
        return "rgba("+r+","+g+","+b+","+opacity+")";
    }
        
    function drawPoint(ctx,x,y,r,color){
        ctx.save();  
        ctx.beginPath();
        ctx.lineWidth=1;
        ctx.fillStyle=hexToCanvasColor(color,1);
        ctx.arc(x,y,r,0.0,2*Math.PI,false);
        ctx.closePath();
        ctx.stroke();
        ctx.fill();
        ctx.restore();
    }
    function getControlPoints(x0,y0,x1,y1,x2,y2,t){
        //  x0,y0,x1,y1 are the coordinates of the end (knot) pts of this segment
        //  x2,y2 is the next knot -- not connected here but needed to calculate p2
        //  p1 is the control point calculated here, from x1 back toward x0.
        //  p2 is the next control point, calculated here and returned to become the 
        //  next segment's p1.
        //  t is the 'tension' which controls how far the control points spread.
        
        //  Scaling factors: distances from this knot to the previous and following knots.
        var d01=Math.sqrt(Math.pow(x1-x0,2)+Math.pow(y1-y0,2));
        var d12=Math.sqrt(Math.pow(x2-x1,2)+Math.pow(y2-y1,2));
       
        var fa=t*d01/(d01+d12);
        var fb=t-fa;
      
        var p1x=x1+fa*(x0-x2);
        var p1y=y1+fa*(y0-y2);

        var p2x=x1-fb*(x0-x2);
        var p2y=y1-fb*(y0-y2);  
        
        return [p1x,p1y,p2x,p2y];
    }    
    

function drawSpline(ctx,pts,t,color,lwidth,drawPoints){
    ctx.lineWidth=lwidth;
    ctx.save();
    var cp=[];   // array of control points, as x0,y0,x1,y1,...
    var n=pts.length;
    if (n>2) {

    for(var i=0;i<n-2;i++){
        cp=cp.concat(getControlPoints(pts[i].x,pts[i].y,pts[i+1].x,pts[i+1].y,pts[i+2].x,pts[i+2].y,t));
    }    
    for(var i=1;i<pts.length-1;i++){
        ctx.strokeStyle=hexToCanvasColor(color,1);       
        ctx.beginPath();
        ctx.moveTo(pts[i].x,pts[i].y);
        ctx.bezierCurveTo(cp[4*i-2],cp[4*i-1],cp[4*i],cp[4*i+1],pts[i+1].x,pts[i+1].y);
        ctx.stroke();
        ctx.closePath();
    }
    //  For open curves the first and last arcs are simple quadratics.
    ctx.strokeStyle=hexToCanvasColor(color,0.75); 
    ctx.beginPath();
    ctx.moveTo(pts[0].x,pts[0].y);
    ctx.quadraticCurveTo(cp[0],cp[1],pts[1].x,pts[1].y);
    ctx.stroke();
    ctx.closePath();
        
    ctx.strokeStyle=hexToCanvasColor(color,0.75); 
    ctx.beginPath();
    ctx.moveTo(pts[n-1].x,pts[n-1].y);
    ctx.quadraticCurveTo(cp[4*n-10],cp[4*n-9],pts[n-2].x,pts[n-2].y);
    ctx.stroke();
    ctx.closePath();
    ctx.restore();
    }
    if (drawPoints)
    {
    	for(var i=0;i<n;i++){
    		drawPoint(ctx,pts[i].x,pts[i].y,2.5,"#ffff00");
    	}
    }
}

function DateToPosX(weekDay, hour, minute) {
	  var posX = startPosX;
	  
	  switch(weekDay) {
	    case "Mon":
	        break;
	    case "Tue":
	        posX += 1 * dayWidth;
	        break;
	    case "Wed":
	    	posX += 2 * dayWidth;
	        break;
	    case "Thu":
	    	posX += 3 * dayWidth;
	        break;
	    case "Fri":
	    	posX += 4 * dayWidth;
	        break;
	    case "Sat":
	    	posX += 5 * dayWidth;
	        break;
	    case "Sun":
	    	posX += 6 * dayWidth;
	        break;    
	  }
	  
	posX += hour * hourWidth;
	posX += minute * hourWidth /60;
	
	return posX;
	}

  function assessWillingness(x1, y1, x2, y2, x) {
	 return y = (y2-y1)*(x-x1)/(x2-x1)+y1;
  }

  function getCurrentTime(posX) {
	  var relativePosX = posX - startPosX;
	  var weekDay; 
	  var hour;
	  var minute;
	  
	  switch(Math.floor(relativePosX / dayWidth) % 7) {
	    case 0:
	        weekDay = "Mon";
	        break;
	    case 1:
	        weekDay = "Tue";
	        break;
	    case 2:
	        weekDay = "Wed";
	        break;
	    case 3:
	        weekDay = "Thu";
	        break;
	    case 4:
	        weekDay = "Fri";
	        break;
	    case 5:
	        weekDay = "Sat";
	        break;
	    case 6:
	        weekDay = "Sun";
	        break;    
	  }
	  relativePosX = relativePosX - Math.floor(relativePosX / dayWidth) * dayWidth;
	  hour = Math.floor(relativePosX / hourWidth);
	  relativePosX = relativePosX - Math.floor(relativePosX / hourWidth) * hourWidth;
	  minute = Math.floor(relativePosX / (hourWidth/60)); 
	  
	return weekDay + ", " + hour.toString() + ":" + minute.toString();
  }  
  
  function getDay(posX) {
	  var relativePosX = posX - startPosX;
	  var weekDay; 	  
	  switch(Math.floor(relativePosX / dayWidth) % 7) {
	    case 0:
	        weekDay = "Mon";
	        break;
	    case 1:
	        weekDay = "Tue";
	        break;
	    case 2:
	        weekDay = "Wed";
	        break;
	    case 3:
	        weekDay = "Thu";
	        break;
	    case 4:
	        weekDay = "Fri";
	        break;
	    case 5:
	        weekDay = "Sat";
	        break;
	    case 6:
	        weekDay = "Sun";
	        break;    
	  }
	  return weekDay;
  }

  function getDayNumber(posX) {
	  var relativePosX = posX - startPosX;
	  var weekDay = Math.floor(relativePosX / dayWidth) % 7;
	  return weekDay;
  }
  
  function getHour(posX) {
	  var relativePosX = posX - startPosX;
	  relativePosX = relativePosX - Math.floor(relativePosX / dayWidth) * dayWidth;
	  var hour = Math.floor(relativePosX / hourWidth);
	  return hour;
  }  
  
  function getMinute(posX) {
	  var relativePosX = posX - startPosX;
	  relativePosX = relativePosX - Math.floor(relativePosX / dayWidth) * dayWidth;
	  relativePosX = relativePosX - Math.floor(relativePosX / hourWidth) * hourWidth;
	  var minute = Math.floor(relativePosX / (hourWidth/60)); 
	  return minute;
  }  
  
  function roundToHalfHour(posX) {
	  
	  if (posX>=drawingLimitX) {
		posX = drawingLimitX;  
	  } 
	  else if (posX <=startPosX) {
		  posX = startPosX;
	  }	 
	  else {	  
		  var minute = getMinute(posX);
		  var hour = getHour(posX);
		  var day = getDayNumber(posX);
	
		  if (minute<15) 
		  {
			  posX = startPosX + dayWidth*day + hourWidth*hour; 
		  }
		  else if (minute>=15 && minute<45) 
		  {
			  posX = startPosX + dayWidth*day + hourWidth*hour + hourWidth/2; 
		  }
		  if (minute>=45) 
		  {
			  posX = startPosX + dayWidth*day + hourWidth*hour + hourWidth; 
		  }	
	  }
		  
	  return posX;
  } 
  
  function adjustPosY(posY) {
	  if (posY <= drawingLimitY) {
		  posY = drawingLimitY;  
	  } 
	  if (posY >= startPosY) {
		  posY = startPosY;
	  }	 
	  return posY;
  }
  

  function getCurrentWillingness(posY) {		  
	return (startPosY - posY) / (2 * halfHeight);
  }  

  function willingnessToPosY(willingness) {		  
		return startPosY - 2 * halfHeight * willingness;
	  }    
  
  function getMousePos(canvas, evt) {
	    var rect = canvas.getBoundingClientRect();
	    return {
	      x: evt.clientX - rect.left,
	      y: evt.clientY - rect.top
	    };
	  } 

  function adjustToCanvas(mousePosition) {		  
	  mousePosition.x = roundToHalfHour(mousePosition.x);
	  mousePosition.y = adjustPosY(mousePosition.y); 
	  return mousePosition;
	  }   	  

  function replaceIfXExists(mousePosition) {
	  mousePosition = adjustToCanvas(mousePosition);

	  for (var i=0; i<coordinates.length; ++i) {
		  if (coordinates[i].x == mousePosition.x) {
			  coordinates[i].y = mousePosition.y;
			  return;
		  }
	  }
	  coordinates.push(mousePosition);
  }
  
  function coordinatesToJSON(coordinatesArray, userName) {
	  var surveyId = document.getElementById('submitButton').name;
	  var jsonObj = 
	  {
		name:	userName,
		survey_id: surveyId,
		availability: []
	  };  

	  for (var i=0; i<coordinatesArray.length; ++i) 
	  	{
		  jsonObj.availability[i] = 
		  {
			willingness:	getCurrentWillingness(coordinatesArray[i].y),
			weekDay:		getDay(coordinatesArray[i].x),
			hour:			getHour(coordinatesArray[i].x),
			minute:			getMinute(coordinatesArray[i].x)
		  };
		}
	  return jsonObj;
	}
  
  function JSONToCoordinates(jsonObj) {
	  var coordinatesArray = new Array();
      for (var key in jsonObj) {
    	  var user = jsonObj[key]['user'];
    	  coordinatesArray[user] = new Array();
		  for (var i=0; i< jsonObj[key]['entries'].length; ++i) 
		  	{
		  		var weekDay = jsonObj[key]['entries'][i]['weekDay'];
				var hour = jsonObj[key]['entries'][i]['hour'];	
				var minute = jsonObj[key]['entries'][i]['minute'];		
				coordinatesArray[user][i] = {x : DateToPosX(weekDay, hour, minute), y : willingnessToPosY(jsonObj[key]['entries'][i]['availability'])};
			}
	  }
		  	
	  return coordinatesArray;
	}  

  function sendAvailability() {
	var username = document.getElementById('username').value;
	if (surveyInfo['status'] != 'Closed') 
	{ 
		if (coordinates.length>2 && username!='') 
		{ 
		    $.post('handleRequest.php', coordinatesToJSON(coordinates, username), function(data){           
		    	alert(username+', thanks for filling your availability!');
		    
		    }).fail(function() {
		         
		            // just in case posting your form failed
		            alert( "Posting failed." );
		             
		        });
		}
		else {
			alert("Please fill your availability survey!");
		}
	}
	else
	{
		alert("You cannot send your availability to closed survey!");
	}
	        // to prevent refreshing the whole page page
	        return false;	
  	}
 
  function fillMissingAvailabilities() {
	  for (var key in results)  
	  {	  
		  if (results[key][0].x > startPosX) {
			  var tmp = startPosX;
			  while (tmp < results[key][0].x) {
				  var pos = new Object();
				  pos.x = tmp;
				  pos.y = startPosY;
				  results[key].push(pos);
				  tmp += hourWidth/2;
			  }	  
		  }
		  
		  results[key].sort(function(a,b) { return a.x - b.x; } );

		  var len = results[key].length
		  for (var i=0; i<len - 1; ++i) 
		  {
			  if (results[key][i+1].x - results[key][i].x > hourWidth/2) 
			  {
				  var tmp = results[key][i].x + hourWidth/2;
				  while (tmp < results[key][i+1].x) {
					  var pos = new Object();
					  pos.x = tmp;
					  pos.y = assessWillingness(results[key][i].x, results[key][i].y, results[key][i+1].x, results[key][i+1].y, pos.x);
					  results[key].push(pos);
					  tmp += hourWidth/2;
				  }
				  
			  }
			  
		  }
		  results[key].sort(function(a,b) { return a.x - b.x; } );
		  
		  len = results[key].length;
		  if (results[key][len-1].x < drawingLimitX) {
			  var tmp = results[key][len-1].x + hourWidth/2;
			  while (tmp <= drawingLimitX) {
				  var pos = new Object();
				  pos.x = tmp;
				  pos.y = startPosY;
				  results[key].push(pos);
				  tmp += hourWidth/2;
			  }  
		  }	
		  results[key].sort(function(a,b) { return a.x - b.x; } );	 
	  }
	  
  
  }

  function countResult() 
  {
	var len;
  	for (var key in results) { 
  		len = results[key].length;
  	};
	for (var i=0; i<len; ++i) 
	{
		var sum=0;
		var resultsLen=0;
		for (var k in results)
		{
			++resultsLen;
			sum += results[k][i].y;
		}
		var mean = new Object();
		mean.x = results[k][i].x;
		mean.y = sum / resultsLen;
		result.push(mean);
	}
	result.sort(function(a,b) { return a.x - b.x; } );

  }

  function fillSurveyInfo() 
  {	
  	var el1 = document.getElementById('surveyName');
  	var el2 = document.getElementById('createdBy');
  	var el3 = document.getElementById('eventLength');
    var el4 = document.getElementById('surveyStatus');

  	var surveyName = document.createTextNode(surveyInfo['survey_name']);
  	var createdBy = document.createTextNode('Created by '+surveyInfo['creator_name']+'.');
  	var eventLength = document.createTextNode('Duration: '+surveyInfo['length']+'h');
    var status = document.createTextNode('Status: '+surveyInfo['status']);
    
  	el1.appendChild(surveyName);
  	el2.appendChild(createdBy);
  	el3.appendChild(eventLength);
  	el4.appendChild(status);
  }  
  
  function getSurveyInfo()
  {
	  var surveyId = document.getElementById('submitButton').name;
	  var message = {survey_id: surveyId};
	  $.post('getSurveyInfo.php', message, function(data) {
            
            // show the response
            surveyInfo = JSON.parse(data);

            fillSurveyInfo();
            deleteButtonIfClosed();
             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;		  
  }
  
  function closeSurvey()
  {
	  var surveyId = document.getElementById('submitButton').name;
	  var message = {survey_id: surveyId};
	  $.post('closeSurvey.php', message, function(data) {
            
		  var res = JSON.parse(data);
		  surveyInfo['status'] = res['status'];
		  var el1 = document.getElementById('surveyStatus');
          el1.removeChild(el1.firstChild);
          var status = document.createTextNode('Status: '+surveyInfo['status']);
          el1.appendChild(status);
          	
            
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;		  
  }  

  function markBestTime() 
  {
	var eventLength = surveyInfo['length']*2;
	var bestMean = 9999999;
	var startX;
	var endX;
	for (var i=0; i<result.length - eventLength; ++i)
	{
		var sum=0;
		for (var j=i; j<=i+eventLength; ++j)
		{
			sum+=result[j].y;
		}
		if (bestMean>sum/eventLength) {
			bestMean = sum/eventLength;
			startX = i;
			endX = i+eventLength;
		}
	}
	var bestResult = result.slice(startX, endX);
	drawSpline(ctx,bestResult,t, "#FF0000", 8, false);
	
  }
  
  function printResults() {		  
    ctx.clearRect(0,0,canvas.width,canvas.height);
    var s=0;
    for (var key in results) {
    	++s;
    }
    canvas.height = originalCanvasHeight + 20*s;
    //canvas.parentNode.style.height+= 50;
    //canvas.height += 50;
    //document.getElementById('survey').height += 50;
    drawChart(ctx);
    var i=0;
    var j=0;
    var legendStartY = startPosY + 50;
    var legendStartX = startPosX;
	for (var key in results) {
		var mod = i%4;
		if (i>0 && mod == 0) {
			j++;
		}
		ctx.lineWidth=4;
		var colorNum = i % colors.length;
		ctx.strokeStyle=hexToCanvasColor(colors[colorNum],1); 
		ctx.beginPath();
	    ctx.moveTo(legendStartX + j*200, legendStartY+mod*20);
	    ctx.lineTo(legendStartX + j*200 + 30 , legendStartY+mod*20);
	    ctx.stroke();
	    ctx.closePath();    
	    ctx.font = '10pt Calibri';
	    ctx.fillStyle = 'black';
	    ctx.fillText(key, legendStartX + j*200 + 35, legendStartY+mod*20);
	    drawSpline(ctx,results[key],t, colors[colorNum], 2, false);
	   	++i;
	}
    
	fillMissingAvailabilities();
	countResult();
	ctx.lineWidth=8;
	ctx.strokeStyle=hexToCanvasColor("#0000AA",1); 
	ctx.beginPath();
	var mod = i%4;
	if (i>0 && mod == 0) {
		j++;
	}
	ctx.moveTo(legendStartX + j*200, legendStartY+mod*20);
    ctx.lineTo(legendStartX + j*200 + 30 , legendStartY+mod*20);
    ctx.stroke();
    ctx.closePath();    
    ctx.font = '10pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText('Survey result', legendStartX + j*200 + 35, legendStartY+mod*20);
    ++i;
	drawSpline(ctx,result,t, "#0000AA", 8, false);
	markBestTime();	
	ctx.lineWidth=8;
	ctx.strokeStyle=hexToCanvasColor("#FF0000",1); 
	ctx.beginPath();
	var mod = i%4;
	if (i>0 && mod == 0) {
		j++;
	}
	ctx.moveTo(legendStartX + j*200, legendStartY+mod*20);
    ctx.lineTo(legendStartX + j*200 + 30 , legendStartY+mod*20);
    ctx.stroke();
    ctx.closePath();    
    ctx.font = '10pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText('BEST EVENT TIME', legendStartX + j*200 + 35, legendStartY+mod*20);
  }
    

  function getResults() {
	  var surveyId = document.getElementById('submitButton').name;
	  var message = {survey_id: surveyId};
	  $.post('getResults.php', message, function(data) {
            
            // show the response
		  	results = {};
		  	result = [];
		  	if (data) {
            presentedResults = true;
		  	var jsonObj = JSON.parse(data);
            results = JSONToCoordinates(jsonObj);
            printResults(); 
		    } else 
			{
		    	presentedResults = false;
		    	alert("There's no responses yet!");
			}

             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;	
  	}	  

  canvas.addEventListener('mousemove', function(evt) {
	 if (!presentedResults)
	 {
	    var mousePos = getMousePos(canvas, evt);
	    mousePos = adjustToCanvas(mousePos);

	    ctx.clearRect(0,0,canvas.width,canvas.height);
	    drawChart(ctx);
	    drawSpline(ctx,coordinates,t, "#AA00AA", 4, true);
	    drawPoint(ctx,mousePos.x,mousePos.y,2.5,"#ffff00");
	    ctx.lineWidth=1;
	    ctx.setLineDash([1,5]);
	        
	    ctx.beginPath();
	    ctx.moveTo(mousePos.x,mousePos.y);
	    ctx.lineTo(mousePos.x,startPosY);
	    ctx.stroke();
	    ctx.closePath();
	        
	    ctx.beginPath();
	    ctx.moveTo(mousePos.x,mousePos.y);
	    ctx.lineTo(startPosX,mousePos.y);
	    ctx.stroke();
	    ctx.closePath();
	    ctx.setLineDash([0,0]);	   
	        
        ctx.font = '10pt Calibri';
        ctx.fillStyle = 'black';
        var currentTime = getCurrentTime(mousePos.x);
        var currentWillingness = getCurrentWillingness(mousePos.y);	
        ctx.fillText(currentTime, mousePos.x +5 ,mousePos.y - 15);
        ctx.fillText(currentWillingness, mousePos.x +5 ,mousePos.y);
	 }
    }, false);  
  
  canvas.addEventListener('mousedown', function(evt) {
	if (!presentedResults)
	{
		var mousePos = getMousePos(canvas, evt);
	
	    replaceIfXExists(mousePos);
	    coordinates.sort(function(a,b) { return a.x - b.x; } );
	    ctx.clearRect(0,0,canvas.width,canvas.height);
	    drawChart(ctx);
	    drawSpline(ctx,coordinates,t, "#AA00AA", 4, true);
	}
  }, false);